package com.shaoshaohuo.app.ui;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.SshApplication;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.LoginEntity;
import com.shaoshaohuo.app.entity.SmsCodeEntity;
import com.shaoshaohuo.app.entity.UserInfoEntity;
import com.shaoshaohuo.app.framework.AccountManager;
import com.shaoshaohuo.app.framework.SharedPreferencesHelper;
import com.shaoshaohuo.app.net.HttpConfig.WebPage;
import com.shaoshaohuo.app.net.HttpRequest;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.net.ShopHttpConfig;
import com.shaoshaohuo.app.utils.Okhttputils;
import com.shaoshaohuo.app.utils.ToastUtil;
import com.shaoshaohuo.app.utils.im.IMFactory;
import com.shaoshaohuo.app.wxapi.Constants;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;

import java.io.IOException;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import okhttp3.Call;
import okhttp3.Response;

/**
 * @version 1.0
 * @author: yusonglin
 * @类 说 明:
 * @创建时间：2015年7月24日 下午2:30:05
 */
public class LoginActivity extends BaseActivity implements OnClickListener, CompoundButton.OnCheckedChangeListener {

    public static final String TAG_IS_CAN_NOT_BACK = "TAG_IS_CAN_NOT_BACK";// 标记是否可以回退

    private EditText mPhoneEdit;
    private EditText mInvestCodeEdit;
    private EditText mAuthcodeEdit;
    private Button mAuthcodeButton;
    private Button mNextButton;
    private LinearLayout layoutLoginInvest;

    private CheckBox mAgreementCb;
    private TextView mAgreementText;

    protected boolean isgetCode = false;

    private String phone;
    private boolean isvisble;
    private View decorView;
    private LinearLayout login_src;
    private ScrollView login_scrollview;
    private int scheight;
    private Handler handler = new Handler();
    private IWXAPI msgApi;
    private PayReq req;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        msgApi = WXAPIFactory.createWXAPI(LoginActivity.this, Constants.APP_ID);
        req = new PayReq();
        View viewById = findViewById(R.id.login_ac_lintop);
//        //B2000000
        changeTransltestaus(viewById, this, TransltestausModel.NoePicter, Color.parseColor("#efeff4"));
//        AccountManager.logout(this);
        initView();
        setUpView();
        initListeners();
        mNextButton.setEnabled(true);
        mNextButton.setTextColor(Color.WHITE);
        decorView = getWindow().getDecorView();
        isvisble = false;
        decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                decorView.getWindowVisibleDisplayFrame(rect);
                //计算出可见屏幕的高度
                int displayHight = rect.bottom - rect.top;
                //获得屏幕整体的高度
                int hight = decorView.getHeight();
                //获得键盘高度
                int keyboardHeight = hight - displayHight;
                boolean visible = (double) displayHight / hight < 0.8;
                if (visible) {
                    //当前状态是键盘谈起，根据数据设置scrollview的滚动
//                    ToastUtil.toast("弹起，高度为" + keyboardHeight);
                    isvisble = true;
                    int bottom = login_src.getBottom();
                    int bottmheight = getResources().getDisplayMetrics().heightPixels - bottom;
                    Log.d("TAG", "onGlobalLayout: " + bottom + "height" + keyboardHeight + "bottmheight" + bottmheight);
                    scheight = keyboardHeight - bottmheight;
                    Log.e("TAG", "onGlobalLayout: " + scheight);
                    if (scheight > 0) {
                        login_scrollview.setTranslationY(-scheight);
                    } else {
                        scheight = 0;
                    }
                }
                if (isvisble && !visible) {
                    isvisble = false;
                    login_scrollview.setTranslationY(0);
                    scheight = 0;
                }


            }
        });
    }

    private void initListeners() {
        mPhoneEdit.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 11) {
                    if ("".equals(SharedPreferencesHelper.getString(s.toString(), ""))) {
                        layoutLoginInvest.setVisibility(View.GONE);
                    }
                } else {
                    layoutLoginInvest.setVisibility(View.GONE);
                }
            }

        });
    }

    private void initView() {
        mPhoneEdit = (EditText) this.findViewById(R.id.edittext_phone);
        mInvestCodeEdit = (EditText) this.findViewById(R.id.edittext_invest_code);
        mAuthcodeEdit = (EditText) this.findViewById(R.id.edittext_authcode);
        mAuthcodeButton = (Button) this.findViewById(R.id.button_authcode);
        mNextButton = (Button) this.findViewById(R.id.button_next);
        mAgreementCb = (CheckBox) this.findViewById(R.id.cb_agreement);
        mAgreementText = (TextView) this.findViewById(R.id.textview_agreement);
        layoutLoginInvest = (LinearLayout) this.findViewById(R.id.layout_login_invest);
        login_src = (LinearLayout) findViewById(R.id.login_sc);
        login_scrollview = (ScrollView) findViewById(R.id.login_scrollview);
    }

    private void setUpView() {
        Intent intent = getIntent();
        if (!intent.getBooleanExtra(TAG_IS_CAN_NOT_BACK, false)) {
        }

        mAuthcodeButton.setOnClickListener(this);
        mNextButton.setOnClickListener(this);
        mAgreementText.setOnClickListener(this);
        mAgreementCb.setOnCheckedChangeListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.textview_agreement:
                Intent intent = new Intent(this, WebBrowserActivity.class);
                intent.putExtra(WebBrowserActivity.TITLE, "注册协议");
                intent.putExtra(WebBrowserActivity.URL, WebPage.REGISTER_AGREEMENT);
                startActivity(intent);
                break;
            case R.id.button_authcode:
                getAuthcode();
                break;
            case R.id.button_next:

//                startLoadingDialog();
                phone = mPhoneEdit.getText().toString().trim();
                String authcode = mAuthcodeEdit.getText().toString().trim();
                String investCode = mInvestCodeEdit.getText().toString().trim();
                final String phone = mPhoneEdit.getText().toString().trim();

                if (TextUtils.isEmpty(phone)) {
                    showToast("请输入合格的手机号");
                    return;
                }
                if (TextUtils.isEmpty(authcode)) {
                    showToast("请输入您收到的验证码");
                    return;
                }

                if (!mAgreementCb.isChecked()) {
                    showToast("请同意服务协议");
                    return;
                }

                ShopHttpConfig.Login(this, phone, authcode, new Okhttputils.OkutListener() {
                    @Override
                    public void error(Call call, IOException e) {
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                ToastUtil.toast("登录失败请检查手机号或 验证码是否正确");
//                            }
//                        });
                    }

                    @Override
                    public void error(Call call, int code) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.toast("登录失败请检查手机号或 验证码是否正确");
                            }
                        });
                    }


                    @Override
                    public void suseff(Call call, Response response, Object o) {
                        LoginEntity loginEntity = (LoginEntity) o;
                        String userid = loginEntity.getData().getUserid();
                        String usertype = loginEntity.getData().getUsertype();
                        String usertoken = loginEntity.getData().getUsertoken();
                        String phone1 = loginEntity.getData().getPhone();
                        SharedPreferencesHelper.setString(SharedPreferencesHelper.Field.USER_ID, userid);
                        SharedPreferencesHelper.setString(SharedPreferencesHelper.Field.USER_TOKEN, usertoken);
                        SharedPreferencesHelper.setString(SharedPreferencesHelper.Field.USER_TYPE, usertype);
                        getUserInfo();
//      IMFactory.logout();
                        IMFactory.login(IMFactory.getImId(userid), IMFactory.default_password, null);
//                        JPushInterface.init(LoginActivity.this); // 初始化 JPush
                        JPushInterface.setAlias(LoginActivity.this, phone1,
                                new TagAliasCallback() {
                                    @Override
                                    public void gotResult(int arg0, String arg1, Set<String> arg2) {
                                        Log.e("TAG", "gotResult:====================== " + arg0);

                                    }
                                });
                        MobclickAgent.onProfileSignIn(AccountManager.getUserId());
                        if (usertype.equals("4")) {
                            Intent intent1 = new Intent();
                            intent1.setClass(LoginActivity.this,
                                    OperateActivity.class);
                            startActivity(intent1);
                            finish();
                            return;
                        }
                        if (usertype.equals("2")) {
                            Intent intent1 = new Intent();
                            intent1.setClass(LoginActivity.this,
                                    CarDriver.class);
                            startActivity(intent1);
                            finish();
                            return;
                        }
                        startActivity(new Intent(LoginActivity.this, MainTabActivity.class));
                        SshApplication.main_state = 2;
                        finish();
                    }
                }, LoginEntity.class);
//                startActivity(new Intent(LoginActivity.this, MainTabActivity.class));
//                SshApplication.main_state = 2;
//                finish();
//                if (TextUtils.isEmpty(phone) || !StringHelper.isPhoneNumber(phone)) {
//                    showToast("请输入合格的手机号");
//                    return;
//                }
//                if (TextUtils.isEmpty(authcode)) {
//                    showToast("请输入您收到的验证码");
//                    return;
//                }
//
//                if (!mAgreementCb.isChecked()) {
//                    showToast("请同意服务协议");
//                    return;
//                }
//
//                ShopHttpConfig.Login(this, phone, authcode, new Okhttputils.OkutListener() {
//                    @Override
//                    public void error(Call call, IOException e) {
//
//                    }
//
//                    @Override
//                    public void error(Call call, int code) {
//
//                    }
//
//                    @Override
//                    public void suseff(Call call, Response response, Object o) {
//                        LoginEntity loginEntity = (LoginEntity) o;
//                        String userid = loginEntity.getData().getUserid();
//                        String usertoken = loginEntity.getData().getUsertoken();
//                        SharedPreferencesHelper.setString(SharedPreferencesHelper.Field.USER_ID, userid);
//                        SharedPreferencesHelper.setString(SharedPreferencesHelper.Field.USER_TOKEN, usertoken);
//                        startActivity(new Intent(LoginActivity.this, MainTabActivity.class));
//                        SshApplication.main_state = 2;
//                        finish();
//                    }
//                }, LoginEntity.class);

//                RequestService.getInstance().login(this, phone, authcode, investCode, UserEntity.class,
//                        new RequestListener() {
//
//                            @Override
//                            public void onSuccess(int requestCode, BaseEntity resultData) {
//                                dismissLoadingDialog();
//                                if (resultData.isOk()) {
//
//                                    UserEntity user = (UserEntity) resultData;
//                                    AccountManager.saveAccount(user);
//                                    getUserInfo();
//                                    SharedPreferencesHelper.setBoolean(LoginActivity.this,
//                                            SharedPreferencesHelper.Field.IS_COME_BACK, true);
//                                    // 记录该手机在本地使用过
//                                    SharedPreferencesHelper.setString(phone, phone);
//
//                                    startActivity(new Intent(LoginActivity.this, MainTabActivity.class));
//                                    SshApplication.main_state = 2;
//                                    finish();
//                                } else {
//                                    showToast(resultData.getMsg());
//                                }
//                            }
//
//                            @Override
//                            public void onFailed(int requestCode, Exception error, String msg) {
//                                dismissLoadingDialog();
//                                showToast(R.string.please_check_network);
//                            }
//                        });

                break;
        }
    }

    private void getUserInfo() {
//        startLoadingDialog();
        RequestService.getInstance().getUserInfo(this, UserInfoEntity.class, new HttpRequest.RequestListener() {
            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                Log.e("TAG", "onSuccess: 获取成功");
                if (resultData.isOk()) {
                    UserInfoEntity entity = (UserInfoEntity) resultData;

                    AccountManager.saveUserInfo(entity.getData());
                    //登录IM
                } else {
                    showToast(resultData.getMsg());
                }
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(R.string.please_check_network);
            }
        });


//        Map<String, String> map = RequestParam.getHeaderParams();
//        Okhttputils.Instanse(this).getnet(map, this, HttpConfig.BASE_HOST_URL + HttpConfig.SubUrl.GET_USER_INFO, new Okhttputils.OkutListener() {
//            @Override
//            public void error(Call call, IOException e) {
//
//            }
//
//            @Override
//            public void error(Call call, int code) {
//
//            }
//
//            @Override
//            public void suseff(Call call, Response response, Object o) {
//                UserInfoEntity userInfoEntity= (UserInfoEntity) o;
//                //数据解析成功
//                dismissLoadingDialog();
//                Log.e("TAG", "onSuccess: 获取成功" );
//
//                    UserInfoEntity entity = (UserInfoEntity) o;
//
//                    AccountManager.saveUserInfo(entity.getData());
//                    //登录IM
//                    IMFactory.logout();
//                    IMFactory.login(IMFactory.getImId(entity.getData().getUserid()), IMFactory.default_password, null);
//                    JPushInterface.init(LoginActivity.this); // 初始化 JPush
//                    JPushInterface.setAlias(LoginActivity.this, entity.getData().getBaseinfo().getMobile(),
//                            new TagAliasCallback() {
//                                @Override
//                                public void gotResult(int arg0, String arg1, Set<String> arg2) {
//                                    Log.e("TAG", "gotResult:====================== " + arg0);
//
//                                }
//                            });
//                    MobclickAgent.onProfileSignIn(AccountManager.getUserId());
//
//
//
//
//            }
//        }, UserInfoEntity.class);


    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    private void getAuthcode() {
        String phone = mPhoneEdit.getText().toString().trim();
        if (TextUtils.isEmpty(phone) && phone.length() < 11) {
            showToast("请输入合格的手机号");
            return;
        }
        startLoadingDialog();
        ShopHttpConfig.SendSms(this, phone, new Okhttputils.OkutListener() {
            @Override
            public void error(Call call, IOException e) {
                dismissLoadingDialog();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.toast("没有网络啦");
                    }
                });
            }

            @Override
            public void error(Call call, final int code) {
                dismissLoadingDialog();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (code == -201) {
                            ToastUtil.toast("手机号不合法");
                        } else if (code == -202) {
                            ToastUtil.toast("操作频繁，请稍后再尝试");
                        } else {
                            ToastUtil.toast(code + "没有网络啦");
                        }

                    }
                });
            }

            @Override
            public void suseff(Call call, Response response, Object o) {
                dismissLoadingDialog();
                SmsCodeEntity sc = (SmsCodeEntity) o;
                isgetCode = true;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        mAuthcodeEdit.setText(codemd5 + "");
                        mAuthcodeButton.setEnabled(false);
                        showToast("验证码已发送");
                        mHandler.removeMessages(0);
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(0), 1 * 1000);
                    }
                });


            }
        });
//        RequestService.getInstance().sendLoginSms(this, phone, SmsCodeEntity.class, new RequestListener() {
//
//            @Override
//            public void onSuccess(int requestCode, BaseEntity resultData) {
//                dismissLoadingDialog();
//                if (resultData.isOk()) {
//                    SmsCodeEntity sc = (SmsCodeEntity) resultData;
//                    isgetCode = true;
//                    SmsCodeEntity.Data data = sc.getData();
//                    final int codemd5 = data.getCodemd5();
//                    Log.e("TAG", "onSuccess: codemd5====" + codemd5);
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            mAuthcodeEdit.setText(codemd5 + "");
//                        }
//                    });
//
//
//                    mAuthcodeButton.setEnabled(false);
//                    mHandler.removeMessages(0);
//                    mHandler.sendMessageDelayed(mHandler.obtainMessage(0), 1 * 1000);
//
//                    showToast("验证码已发送");
//                } else {
//                    showToast(resultData.getMsg());
//                }
//            }
//
//            @Override
//            public void onFailed(int requestCode, Exception error, String msg) {
//                dismissLoadingDialog();
//                showToast(R.string.please_check_network);
//                Log.d("TAG", "onFailed: " + requestCode + "erro" + error + "msg" + msg);
//            }
//        });
    }

    private static final int DEFAULT_SMS_VERIFYCODE_COUNTDOWN_TIME = 60;
    private int mUpdateCount = DEFAULT_SMS_VERIFYCODE_COUNTDOWN_TIME;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                --mUpdateCount;
                if (mUpdateCount > 0) {
                    mAuthcodeButton.setText(String.format("%ds", mUpdateCount));
                    sendMessageDelayed(obtainMessage(0), 1 * 1000);
                    mAuthcodeButton.setEnabled(false);
                } else {
                    mAuthcodeButton.setText("重新发送");
                    mUpdateCount = DEFAULT_SMS_VERIFYCODE_COUNTDOWN_TIME;
                    mAuthcodeButton.setEnabled(true);
                }
            }
        }
    };

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        //chexbox改变监听
//        android.hardware.Camera open = android.hardware.Camera.open();
//        open.takePicture();
        mNextButton.setEnabled(isChecked);

    }
}
